import Const from "./const";

function Util() {
    return {
        sprintf: require('locutus/php/strings/sprintf'),
        date: require('locutus/php/datetime/date'),
        trim: require('locutus/php/strings/trim'),
        parseDate: parseDate,
        clearData: clearData,
        is: is,
        clone: clone,
        time: time,
        convertMoney: convertMoney,
        get: get,
        digitLength: digitLength,
        sortType: sortType,
    };

    function parseDate(date) {
        return parseInt(new Date(date).getTime() / 1000);
    }

    function clearData(data) {
        Object.keys(data).forEach(function (key) {
            if (is('object', data[key])) {
                data[key] = {};
            }
            if (is('array', data[key])) {
                data[key] = [];
            }
            if (is('number', data[key])) {
                data[key] = "";
            }
            if (is('string', data[key])) {
                data[key] = "";
            }
        })
    }

    function is(type, obj) {
        let item;
        item = Object.prototype.toString.call(obj).slice(8, -1);
        return obj !== undefined && obj !== null && item.toLowerCase() === type.toLowerCase()
    }

    function clone(obj) {
        let o;
        if (typeof obj === "object") {
            if (obj === null) {
                o = null;
            } else {
                if (obj instanceof Array) {
                    o = [];
                    for (let i = 0, len = obj.length; i < len; i++) {
                        o.push(clone(obj[i]));
                    }
                } else {
                    o = {};
                    for (let j in obj) {
                        o[j] = clone(obj[j]);
                    }
                }
            }
        } else {
            o = obj;
        }
        return o;
    }

    function time() {
        return parseInt(new Date().getTime() / 1000, 10);
    }

    function convertMoney(money) {
        if (!money) {
            return 0;
        }
        return parseInt(money) * 100;
    }

    function get(obj, key) {
        return key.split(".").reduce(function (o, x) {
            return (typeof o === "undefined" || o === null) ? o : o[x];
        }, obj);
    }

    function digitLength(data, length) {
        return this.sprintf('%0' + length + 'd', data);
    }

    function sortType(prop, order) {
        let sortList = Const.DEVICE_SORT_PROP_LIST;
        let index = sortList.findIndex(item => item === prop);
        // 'ascending'  'descending'
        let temp = 0;
        if(order === 'descending') {
            temp = -1;
        }
        return index > -1 ?  2 * (index + 1) + temp : 1;
    }
}

export default new Util()
